package com.itheima.topic;

import com.itheima.utils.RabbitMqUtil;
import com.rabbitmq.client.*;

import java.io.IOException;


/**
 * @author Administrator
 */
public class Consumer2 {
    /**
     * 定义队列1(queue)
     */
    private static final String TOPIC_QUEUE_2 = "topic_queue_2";

    /**
     * 定义交换机
     */
    private static final String TOPIC_EXCHANGE = "topic_exchange";
    public static void main(String[] args) throws Exception {

        //获取连接
        Connection connection = RabbitMqUtil.newConnection();

        //3.创建频道(信道)
        Channel channel = connection.createChannel();

        //4.创建队列
        channel.queueDeclare(TOPIC_QUEUE_2, true, false, false, null);

        //创建交换机
        channel.exchangeDeclare(TOPIC_EXCHANGE,BuiltinExchangeType.TOPIC);

        //绑定交换机
        /**
         * queueBind(String queue, String exchange, String routingKey)
         * 参数1 queue :队列名称
         * 参数2 exchange : 交换机名称
         * 参数3 routingKey :路由Key,非工作模式和简单模式下不能使用队列名代替 接收路由Key为debug的路由Key
         */
        channel.queueBind(TOPIC_QUEUE_2,TOPIC_EXCHANGE,"item.#");


        //创建消费者；并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                System.out.println("路由key为：" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为：" + envelope.getExchange());
                //消息id
                System.out.println("消息id为：" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("Consumer2接收到的消息为：" + new String(body, "UTF-8"));

            }

        };

        //监听消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数1 queue：队列名称
         * 参数2 autoAck：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认
         * 参数3 callback ：消息接收到后回调
         */
        channel.basicConsume(TOPIC_QUEUE_2, true, consumer);

    }


}
